package com.unionftech.common.webview

import android.content.Context
import android.content.MutableContextWrapper
import android.os.Looper
import com.unionftech.common.utils.LogUtils
import com.unionftech.common.webview.view.BaseWebView
import com.unionftech.common.webview.view.ProgressWebView
import java.util.Stack


class WebViewPool private constructor() {
    companion object {
        private const val TAG = "WebViewPool"

        @Volatile
        private var instance: WebViewPool? = null

        @JvmStatic
        fun getInstance(): WebViewPool {
            return instance ?: synchronized(this) {
                instance ?: WebViewPool().also {
                    instance = it
                }
            }
        }
    }

    //采用Stack进行存储复用
    private val webViewPool = Stack<BaseWebView>()
    private val lock = byteArrayOf()
    private var poolMaxSize = 1

    /**
     * 设置WebView池容量
     */
    fun setMaxPoolSize(size: Int) {
        synchronized(lock) {
            poolMaxSize = size
        }
    }

    /**
     * 初始化WebView 放在WebView池中
     */
    @JvmOverloads
    fun init(context: Context, initSize: Int = poolMaxSize) {
        Looper.getMainLooper().queue.addIdleHandler {
            LogUtils.d(TAG, "init WebViewPool WebViewCacheStack Size = " + webViewPool.size)
            if (webViewPool.size < poolMaxSize) {
                val view = ProgressWebView(MutableContextWrapper(context))
                webViewPool.push(view)
            }
            false
        }
    }

    /**
     * 从pool池中获取WebView
     */
    fun getWebView(context: Context): BaseWebView {
        synchronized(lock) {
            val webView: BaseWebView
            if (webViewPool.size > 0) {
                webView = webViewPool.pop()
                LogUtils.d(TAG, "getWebView from webViewPool")
            } else {
                webView = ProgressWebView(MutableContextWrapper(context))
            }
            val contextWrapper = webView.context as MutableContextWrapper
            contextWrapper.baseContext = context
            return webView
        }
    }

    fun recycle(webView: BaseWebView) {
        //释放资源
        webView.release()
        //根据pool池容量判断是否销毁
        val contextWrapper = webView.context as MutableContextWrapper
        contextWrapper.baseContext = webView.context.applicationContext
        synchronized(lock) {
            if (webViewPool.size < poolMaxSize) {
                webViewPool.push(webView)
            } else {
                webView.destroy()
            }
        }
    }

    fun destroy() {
        synchronized(lock) {
            val iterator = webViewPool.iterator()
            while (iterator.hasNext()) {
                val webView = iterator.next()
                webView?.release()
                webView?.destroy()
            }
        }
    }
}